function [ fimg ] = my_medianFilter( img, w )
%MY_MEDIANFILTER Summary of this function goes here
%   Detailed explanation goes here
fl = floor(w/2); sizePic = size(img);
%building a matrix in the size of the image
fimg = img;
picR = img(:,:,1); picG = img(:,:,2); picB = img(:,:,3); 

%go through the matrix by coulmn
for y=1:sizePic(1)
    for x=1:sizePic(2)
       %##Split in two cases, because CASE1 is more efficient but can't run
       %in CASE 2.##
       %CASE 1: The filterbox will be within the picture's borders
       if (y>fl && x>fl) && (y<sizePic(1)-fl && x<sizePic(2)-fl)
            filterMatR = picR(y-fl:y+fl, x-fl:x+fl);
            filterMatG = picG(y-fl:y+fl, x-fl:x+fl);
            filterMatB = picB(y-fl:y+fl, x-fl:x+fl);

            fimg(y,x,1) = median(reshape(filterMatR, 1, []));
            fimg(y,x,2) = median(reshape(filterMatG, 1, []));
            fimg(y,x,3) = median(reshape(filterMatB, 1, []));
       %CASE 2: The filterbox overlaps the picture's borders
       else
           tmpR = []; tmpG = []; tmpB = [];
           for yf=-w:w
               for xf=-w:w
                   PosX = x+xf; PosY = y+yf;
                   %Is the current possition within the filterbox within
                   %the picture?
                   if (PosY>0 && PosX>0) && ((PosY<=sizePic(1)) && (PosX<=sizePic(2)))
                       tmpR = [tmpR picR(PosY, PosX)];
                       tmpG = [tmpG picG(PosY, PosX)];
                       tmpB = [tmpB picB(PosY, PosX)];
                   end
               end 
               fimg(y,x,1) = median(tmpR); fimg(y,x,2) = median(tmpG); fimg(y,x,3) = median(tmpB);
           end
       end         
    end
end
